package han.cirno.corrupt.util

import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

object StreamUtil {
    @JvmOverloads
    @Throws(IOException::class)
    fun copyStream(inputStream: InputStream, outputStream: OutputStream, bufferSize: Int = 4096) {
        val buffer = ByteArray(bufferSize)
        var read: Int
        while (inputStream.read(buffer).apply { read=this } != -1)
            outputStream.write(buffer, 0, read)
    }

    fun copyFile(from:File,to:File){
        FileInputStream(from).use {i->
            FileOutputStream(to).use {o->
                copyStream(i,o)
            }
        }
    }

    fun readToByteArray(inputStream: InputStream):ByteArray{
        ByteArrayOutputStream().use {
            copyStream(inputStream,it)
            return it.toByteArray()
        }
    }
}
